package Common

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type MyClaims struct {
	Userid   string `json:"userid"`
	Nickname string `json:"nickname"`
	jwt.StandardClaims
}

// EncodeToken 编码
/*
	@Description: 生成 JWT 令牌
	@userid 用户id
	@Nickname 昵称
	@return string 生成的 JWT 令牌
*/
func EncodeToken(userid string, Nickname string) string {
	mySigningKey := []byte("cai")
	c := new(MyClaims)
	c.Userid = userid

	c.Nickname = Nickname
	c.StandardClaims = jwt.StandardClaims{
		ExpiresAt: time.Now().Unix() + 24*60*60*30, // 30天过期
		Issuer:    "cai",
	}
	t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	s, e := t.SignedString(mySigningKey)
	if e != nil {
		fmt.Println(e)
		return ""
	}
	fmt.Println(s)
	return s
}

// CodeToken 解码
/*
	@Description: 解析 JWT 令牌
	@s token 令牌
	@return string userid
	@return string nickname
	@return error 错误信息
*/
func CodeToken(s string) (string, string, error) {
	mySigningKey := []byte("cai")
	token, err := jwt.ParseWithClaims(s, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		return "", "", err
	}
	claims := token.Claims.(*MyClaims)
	return claims.Userid, claims.Nickname, nil
}
